<template>
  <div class="wrapper">
    <button @click="rotateCoordinatesAndSize(0, 90)">旋转</button>
    <div>
      0 <br />
      90 <br />
      180 <br />
      270
    </div>
    <div id="outer">
      <div id="inner"></div>
    </div>
  </div>
</template>

<script>
export default {
  name: "RectangleTest",
  components: {},
  props: {},
  data() {
    return {};
  },
  watch: {},
  computed: {},
  methods: {
    rotateCoordinatesAndSize(
      rotationAngleBeforeRotation,
      rotationAngleAfterRotation
    ) {
      const radiansBefore = (rotationAngleBeforeRotation * Math.PI) / 180;
      const radiansAfter = (rotationAngleAfterRotation * Math.PI) / 180;
      const cosBefore = Math.cos(radiansBefore);
      const sinBefore = Math.sin(radiansBefore);
      const cosAfter = Math.cos(radiansAfter);
      const sinAfter = Math.sin(radiansAfter);

      const outerDiv = document.getElementById("outer");
      const innerDiv = document.getElementById("inner");

      // 获取内层 div 的初始坐标和宽高
      const { left, top, width, height } = innerDiv.getBoundingClientRect();

      // 将坐标转换为以旋转前中心为原点的坐标
      const offsetXBefore = left - outerDiv.offsetWidth / 2;
      const offsetYBefore = top - outerDiv.offsetHeight / 2;

      // 根据旋转角度调整坐标位置和尺寸
      const rotatedXAfter =
        offsetXBefore * cosAfter -
        offsetYBefore * sinAfter +
        outerDiv.offsetWidth / 2;
      const rotatedYAfter =
        offsetXBefore * sinAfter +
        offsetYBefore * cosAfter +
        outerDiv.offsetHeight / 2;
      const rotatedWidthAfter =
        rotationAngleAfterRotation === 90 || rotationAngleAfterRotation === 270
          ? height
          : width;
      const rotatedHeightAfter =
        rotationAngleAfterRotation === 90 || rotationAngleAfterRotation === 270
          ? width
          : height;

      // 设置外层和内层 div 的旋转后坐标和尺寸
      outerDiv.style.transform = `rotate(${rotationAngleAfterRotation}deg)`;
      innerDiv.style.left = rotatedXAfter + "px";
      innerDiv.style.top = rotatedYAfter + "px";
      innerDiv.style.width = rotatedWidthAfter + "px";
      innerDiv.style.height = rotatedHeightAfter + "px";
    },
  },
  created() {},
  mounted() {},
};
</script>
<style>
#outer {
  position: relative;
  width: 800px;
  height: 400px;
  border: 1px solid black;
}

#inner {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 200px;
  height: 200px;
  background-color: red;
}
</style>
